import { refreshTokenAxios } from '@/api/login';
import type { UserStore } from '@/pinia/modules/user';
import type { AppStore } from '@/pinia/modules/app';
/** 自动登录的队列 */
let refreshList: ((res: { code: number; msg: string }) => void)[] = [];
let refreshing = false;
/**
 * 自动登录
 */
export function refreshToken(userStore: UserStore, appStore: AppStore): Promise<string> {
  return new Promise<string>((resolve, reject) => {
    refreshList.push((state) => {
      try {
        state.code === 200 ? resolve(state.msg) : reject(false);
      } catch (error) {}
    });
    if (!refreshing) {
      refreshing = true;
      _refreshToken(userStore, appStore)
        .then((res) => {
          refreshList.forEach((cb) => {
            cb(res);
          });
          refreshing = false;
          refreshList = [];
        })
        .catch(() => {
          refreshList.forEach((cb) => {
            cb({ code: 40003, msg: '代码错误，SX2004' });
          });
          refreshing = false;
          refreshList = [];
        });
    }
  });
}

/**
 * 自动登录
 */
async function _refreshToken(userStore: UserStore, appStore: AppStore) {
  try {
    const res = await refreshTokenAxios(userStore.refresh_token || '');
    userStore.setAccessToken(res.data.accessToken);
    userStore.setRefreshToken(res.data.refreshToken);

    if (res.data.roleId === 117) {
      appStore.setHomeRoute('/ledger-management/drama-data-statistics');
    } else {
      appStore.setHomeRoute('/home');
    }

    return Promise.resolve({ code: 200, msg: res.data.accessToken });
  } catch (error) {
    return Promise.reject({ code: 40003, msg: '代码错误，SX2003' });
  }
}
